//
//  UIScrollView+MJRefreshEX.m
//  lTTheOne
//
//  Created by 1 on 2024/4/27.
//

#import "UIScrollView+MJRefreshEX.h"
#import "MJRefresh.h"
#import "TXAdapter.h"
#import <objc/runtime.h>

typedef void(^RefreshBlock)(NSInteger pageIndex);
typedef void(^LoadMoreBlock)(NSInteger pageIndex);

@interface UIScrollView ()

/**页码*/
@property (assign, nonatomic) NSInteger pageIndex;
/**下拉时候触发的block*/
@property (nonatomic, copy) RefreshBlock refreshBlock;
/**上拉时候触发的block*/
@property (nonatomic, copy) LoadMoreBlock loadMoreBlock;


@end

@implementation UIScrollView (MJRefreshEX)

- (void)addHeaderWithHeaderWithBeginRefresh:(BOOL)beginRefresh animation:(BOOL)animation refreshBlock:(void(^)(NSInteger pageIndex))refreshBlock{

    __weak typeof(self) weakSelf = self;
    self.refreshBlock = refreshBlock;
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf resetPageNum];
    
        if (weakSelf.refreshBlock) {
            weakSelf.refreshBlock(weakSelf.pageIndex);
        }
        [weakSelf endHeaderRefresh];
    }];
    
    if (beginRefresh && animation) {
        //有动画的刷新
        [self beginHeaderRefresh];
    }else if (beginRefresh && !animation){
        //刷新，但是没有动画
        [self.mj_header executeRefreshingCallback];
    }
    
    header.mj_h = 70.0;
    self.mj_header = header;
}


- (void)addGifHeaderWithHeaderWithgif:(NSString*)gif Insettop:(CGFloat)Insettop duration:(CGFloat)duration refreshBlock:(void(^)(NSInteger pageIndex))refreshBlock{

    __weak typeof(self) weakSelf = self;
    self.refreshBlock = refreshBlock;
    
    NSArray *imageNames = [self loadGifImageArr:gif];
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1* NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf resetPageNum];
            [weakSelf endHeaderRefresh];
            [weakSelf endFooterRefresh];
            if (weakSelf.refreshBlock) {
                weakSelf.refreshBlock(weakSelf.pageIndex);
            }
        });
    }];
    
    header.stateLabel.hidden = YES;
    header.lastUpdatedTimeLabel.hidden = YES;
    header.ignoredScrollViewContentInsetTop =Insettop;
    [header setImages:imageNames duration:duration forState:MJRefreshStateIdle];
//    [header setImages:imageNames duration:0.9 forState:MJRefreshStatePulling];
    [header setImages:imageNames duration:duration forState:MJRefreshStateWillRefresh];
    [header setImages:imageNames duration:duration forState:MJRefreshStateRefreshing];
    self.mj_header = header;
}


- (void)addFooterWithWithHeaderWithAutomaticallyRefresh:(BOOL)automaticallyRefresh type:(int)type loadMoreBlock:(void(^)(NSInteger pageIndex))loadMoreBlock{
    
    self.loadMoreBlock = loadMoreBlock;
    __weak typeof(self) weakSelf = self;
    
    if (automaticallyRefresh) {
        
        if (type == 0) {
            
            MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
                
                weakSelf.pageIndex += 1;
                if (weakSelf.loadMoreBlock) {
                    weakSelf.loadMoreBlock(weakSelf.pageIndex);
                }
                [weakSelf endHeaderRefresh];
                [weakSelf endFooterRefresh];
                
            }];
            footer.backgroundColor = [UIColor blueColor];
            self.mj_footer = footer;
            footer.hidden = YES;
         
        } else {
            
            MJRefreshAutoNormalFooter * footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                weakSelf.pageIndex += 1;
                if (weakSelf.loadMoreBlock) {
                    weakSelf.loadMoreBlock(weakSelf.pageIndex);
                }
                [weakSelf endHeaderRefresh];
                [weakSelf endFooterRefresh];
            }];
            
            footer.automaticallyRefresh = automaticallyRefresh;
//            footer.ignoredScrollViewContentInsetBottom = footer.mj_h+InsetBottom; //不显示他的高度
            self.mj_footer = footer;
        }
        
        
//        footer.stateLabel.font = [UIFont systemFontOfSize:13.0];
//        footer.stateLabel.textColor = [UIColor colorWithWhite:0.400 alpha:1.000];
//        [footer setTitle:@"加载中…" forState:MJRefreshStateRefreshing];
//        [footer setTitle:@"~~这是我的底线啦~~" forState:MJRefreshStateNoMoreData];
        
        
    }
    else{
        MJRefreshBackNormalFooter * footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            weakSelf.pageIndex += 1;
            if (weakSelf.loadMoreBlock) {
                weakSelf.loadMoreBlock(weakSelf.pageIndex);
            }
            [weakSelf endHeaderRefresh];
            [weakSelf endFooterRefresh];
        }];
        
//        footer.stateLabel.font = [UIFont systemFontOfSize:13.0];
//        footer.stateLabel.textColor = [UIColor colorWithWhite:0.400 alpha:1.000];
//        [footer setTitle:@"加载中…" forState:MJRefreshStateRefreshing];
//        [footer setTitle:@"~~这是我的底线啦~~" forState:MJRefreshStateNoMoreData];
        
        self.mj_footer = footer;
    }
   
}

-(void)beginHeaderRefresh {
    
    [self resetPageNum];
    [self.mj_header beginRefreshing];
}

- (void)resetPageNum {
    self.pageIndex = 0;
}

- (void)resetNoMoreData {
    
    [self.mj_footer resetNoMoreData];
}

-(void)endHeaderRefresh {
    
    [self.mj_header endRefreshing];
    [self resetNoMoreData];
}

-(void)endFooterRefresh {
    [self.mj_footer endRefreshing];
}

- (void)endFooterNoMoreData
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.mj_footer endRefreshingWithNoMoreData];
    });
}


static void *pagaIndexKey = &pagaIndexKey;
- (void)setPageIndex:(NSInteger)pageIndex{
    objc_setAssociatedObject(self, &pagaIndexKey, @(pageIndex), OBJC_ASSOCIATION_ASSIGN);
}

- (NSInteger)pageIndex
{
    return [objc_getAssociatedObject(self, &pagaIndexKey) integerValue];
}

static void *RefreshBlockKey = &RefreshBlockKey;
- (void)setRefreshBlock:(void (^)(void))RefreshBlock{
    objc_setAssociatedObject(self, &RefreshBlockKey, RefreshBlock, OBJC_ASSOCIATION_COPY);
}

- (RefreshBlock)refreshBlock
{
    return objc_getAssociatedObject(self, &RefreshBlockKey);
}

static void *LoadMoreBlockKey = &LoadMoreBlockKey;
- (void)setLoadMoreBlock:(LoadMoreBlock)loadMoreBlock{
    objc_setAssociatedObject(self, &LoadMoreBlockKey, loadMoreBlock, OBJC_ASSOCIATION_COPY);
}

- (LoadMoreBlock)loadMoreBlock
{
    return objc_getAssociatedObject(self, &LoadMoreBlockKey);
}



//获取gif动画的每一帧
- (NSArray *)loadGifImageArr:(NSString*)gifStr
{
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:gifStr withExtension:@"gif"];
    
    CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef)fileUrl, NULL);
    size_t gifCount = CGImageSourceGetCount(gifSource);
    NSMutableArray *frames = [[NSMutableArray alloc]init];
    for (size_t i = 0; i< gifCount; i++) {
        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);
        UIImage *image = [UIImage imageWithCGImage:imageRef];
        UIImage *newimage = [self imageResize:image andResizeTo:CGSizeMake(tRealLength(70), tRealLength(70))];
        [frames addObject:newimage];
        CGImageRelease(imageRef);
    }
    return frames;
}


- (UIImage *)imageResize:(UIImage*)img andResizeTo:(CGSize)newSize {
    CGFloat scale = [[UIScreen mainScreen]scale];
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, NO, scale);
    [img drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

@end
